<template>
  <view class="chat-container">
    <!-- 聊天头部 -->
    <view class="chat-header">
      <view class="header-left" @click="goBack">
        <uni-icons type="left" size="20"></uni-icons>
      </view>
      <view class="title">{{ chatInfo.title }}</view>
      <view class="header-right">
        <uni-icons type="more-filled" size="20" color="#666"></uni-icons>
      </view>
    </view>

    <!-- 聊天消息区域 -->
    <scroll-view 
      class="chat-messages" 
      scroll-y="true" 
      :scroll-into-view="lastMessageId"
      :scroll-with-animation="true"
    >
      <view class="chat-date">
        <text>{{ formatDate() }}</text>
      </view>
      
      <view 
        v-for="msg in currentMessages" 
        :key="msg.id" 
        :class="['message', msg.senderId === userId ? 'user' : 'customerService']" 
        :id="'msg-' + msg.id"
      >
        <view class="avatar">
          <image :src="msg.senderId === userId ? '/static/avatar/user.png' : '/static/avatar/service.png'" mode="aspectFill"></image>
        </view>
        <view class="message-content">
          <text>{{ msg.content }}</text>
          <view class="message-time">{{ formatMessageTime(msg.sendTime) }}</view>
        </view>
      </view>

      <view v-if="currentMessages.length === 0" class="no-messages">
        <text>暂无聊天记录，开始发送消息吧</text>
      </view>
    </scroll-view>

    <!-- 输入区域 -->
    <view class="chat-input">
      <view class="input-actions">
        <uni-icons type="sound" size="24" color="#666"></uni-icons>
      </view>
      <input 
        v-model="newMessage" 
        class="input-field"
        placeholder="输入消息..." 
        @confirm="sendMessage"
        :disabled="isSending"
      />
      <view class="input-actions">
        <uni-icons type="emotion" size="24" color="#666" style="margin-right: 20rpx;"></uni-icons>
        <uni-icons type="plusempty" size="24" color="#666"></uni-icons>
      </view>
      <button 
        class="send-btn" 
        @click="sendMessage" 
        v-if="newMessage.trim()"
        :disabled="isSending"
      >
        {{ isSending ? '发送中...' : '发送' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useChatStore } from '../../../store/chatStore'

const chatStore = useChatStore()
const { currentMessages, isSending } = storeToRefs(chatStore)

const chatInfo = ref({})
const newMessage = ref('')
const userId = ref(uni.getStorageSync('userId') || '1') // 假设用户ID存储在本地

// 获取最后一条消息的ID用于滚动
const lastMessageId = computed(() => {
  if (currentMessages.value.length > 0) {
    return 'msg-' + currentMessages.value[currentMessages.value.length - 1].id
  }
  return ''
})

onMounted(() => {
  // 获取上一页传递的数据
  try {
    const query = uni.getLaunchOptionsSync().query;
    
    if (query && query.data) {
      try {
        const parseData = JSON.parse(decodeURIComponent(query.data));
        
        chatInfo.value = {
          ...parseData,
          targetId: Number(parseData.targetId)
        };
        
        loadChatHistory();
      } catch (parseError) {
        uni.showToast({
          title: '参数格式错误',
          icon: 'none'
        });
      }
    } else {
      uni.showToast({
        title: '未获取到聊天参数',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.showToast({
      title: '获取聊天参数失败',
      icon: 'none'
    });
  }
});

// 加载聊天记录
const loadChatHistory = async () => {
  if (!chatInfo.value || !chatInfo.value.targetId) {
    uni.showToast({
      title: '无效的聊天对象ID',
      icon: 'none'
    });
    return;
  }
  
  try {
    await chatStore.loadChatHistory(chatInfo.value.targetId);
  } catch (error) {
    uni.showToast({
      title: '获取聊天记录失败',
      icon: 'none'
    });
  }
};

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || isSending.value) return;
  
  if (!chatInfo.value || !chatInfo.value.targetId) {
    uni.showToast({
      title: '无效的聊天对象ID',
      icon: 'none'
    });
    return;
  }
  
  try {
    const messageDTO = {
      targetId: chatInfo.value.targetId,
      content: newMessage.value.trim(),
      messageType: 'text'
    };
    
    await chatStore.sendNewMessage(messageDTO);
    newMessage.value = '';
  } catch (error) {
    uni.showToast({
      title: error.message || '发送失败',
      icon: 'none'
    });
  }
};

// 返回上一页
const goBack = () => {
  chatStore.clearCurrentChat();
  uni.navigateBack();
};

// 格式化日期
const formatDate = () => {
  const now = new Date();
  return now.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  });
};

// 格式化消息时间
const formatMessageTime = (timeString) => {
  if (!timeString) return '';
  const messageDate = new Date(timeString);
  return messageDate.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};
</script>

<style lang="scss">
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: $bg-color;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background-color: $bg-color-white;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  height: 88rpx;

  .header-left, .header-right {
    width: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 60rpx;
    border-radius: 50%;
    
    &:active {
      background-color: rgba($primary-color, 0.1);
    }
  }

  .title {
    font-size: 32rpx;
    font-weight: 500;
    color: $text-color;
    flex: 1;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.chat-messages {
  flex: 1;
  padding: 120rpx 30rpx 180rpx;
  box-sizing: border-box;

  .chat-date {
    text-align: center;
    margin: 30rpx 0;
    
    text {
      display: inline-block;
      padding: 8rpx 24rpx;
      background-color: rgba($text-color, 0.05);
      color: $text-color-light;
      font-size: 24rpx;
      border-radius: 20rpx;
    }
  }

  .message {
    display: flex;
    align-items: flex-start;
    margin-bottom: 30rpx;
    transition: all 0.3s;
    animation: fadeIn 0.3s ease-out;

    .avatar {
      width: 80rpx;
      height: 80rpx;
      margin: 0 20rpx;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);

      image {
        width: 100%;
        height: 100%;
      }
    }

    .message-content {
      max-width: 66%;
      padding: 20rpx 30rpx;
      border-radius: 20rpx;
      font-size: 28rpx;
      word-break: break-all;
      position: relative;
      
      .message-time {
        font-size: 22rpx;
        color: $text-color-light;
        margin-top: 8rpx;
        text-align: right;
      }
    }

    &.user {
      flex-direction: row-reverse;

      .message-content {
        background-color: $primary-color;
        color: $bg-color-white;
        border-radius: 20rpx 4rpx 20rpx 20rpx;
        
        .message-time {
          color: rgba($bg-color-white, 0.8);
        }
      }
    }

    &.customerService {
      .message-content {
        background-color: $bg-color-white;
        color: $text-color;
        border-radius: 4rpx 20rpx 20rpx 20rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
      }
    }
  }
  
  .no-messages {
    text-align: center;
    margin: 100rpx 0;
    color: $text-color-light;
    font-size: 28rpx;
  }
}

.chat-input {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx;
  background-color: $bg-color-white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  gap: 16rpx;

  .input-actions {
    display: flex;
    align-items: center;
  }

  .input-field {
    flex: 1;
    height: 80rpx;
    padding: 0 30rpx;
    background-color: $bg-color;
    border-radius: 40rpx;
    font-size: 28rpx;
    transition: all 0.3s;
    
    &:focus {
      box-shadow: 0 0 0 2rpx rgba($primary-color, 0.2);
    }
  }

  .send-btn {
    min-width: 120rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: $primary-color;
    color: $bg-color-white;
    border-radius: 40rpx;
    font-size: 28rpx;
    padding: 0 26rpx;
    margin: 0;
    
    &:active {
      background-color: darken($primary-color, 5%);
    }

    &:disabled {
      background-color: rgba($primary-color, 0.5);
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>